<template>
    <HeaderComponent/>
    <div id="BackLink">
      <router-link :to="{name:'Main'}">Return to Main Menu</router-link>
    </div>
  
    <div id="Catalog">
    <div v-if="accountStore.username">
    <form @submit.prevent="handleSubmit">
        <p v-if="signOnMsg" class="error-message">{{ signOnMsg }}</p>
      <table style="width: 40%; margin: 0 auto;">
        <tr>
          <th colspan="2"><h3>User Information</h3></th>
        </tr>

        <tr>
          <td>User ID:</td>
          <td>
            <input
              type="text"
              name="username"
              v-model="form.username"
            />
          </td>
        </tr>

        

        <tr>
          <td>New password:</td>
          <td>
            <input
              type="password"
              id="password"
              name="password"
              v-model="form.password"
              @blur="checkCode"
            />
            <span id="isProperCode">{{ passwordCheck }}</span>
          </td>
        </tr>

        <tr>
          <td>Repeat password:</td>
          <td>
            <input
              type="password"
              id="repeatedPassword"
              name="repeatedPassword"
              v-model="form.repeatPassword"
              @blur="checkRepeatedCode"
            />
            <span id="isRepeatedCode">{{ repeatCheck }}</span>
          </td>
        </tr>
      </table>

      
      <AccountForm v-model="form" />

      <!-- 我的优惠券和订单 -->
      <router-link :to="{ name: 'ListOrder' }">My Orders       </router-link>
      <input type="submit" name="editAccount" value="Save Account Information" />
      <router-link :to="{ name: 'Coupon' }">       My Coupons</router-link>
    </form>

    </div>
<div v-else>
      <p>无法加载用户信息，请确保用户已登录。</p>
</div>
  </div>
    <br><br><br><br><br>
    <FooterComponent/>
    
</template>
    
<script setup>
    import { ref,onMounted } from 'vue';
    // import { useRouter } from 'vue-router';
    import HeaderComponent from '@/components/Header.vue';
    import FooterComponent from '@/components/Footer.vue';
    import AccountForm from '@/components/account/AccountForm.vue';
    import { getUserInfo,updateUserInfo} from '@/api/account.js'; 
    import { useAccountStore }from '@/stores/accountStore'
    
    const accountStore = useAccountStore()
    // const router = useRouter();
    
    const signOnMsg = ref('');
    const form = ref({
      username: '',
      password: '',
      repeatPassword: '',
      email: '',
      firstName: '',
      lastName: '',
      status: ' ',
      address1: '',
      address2: '',
      city: '',
      state: '',
      zip: '',
      country: '',
      phone: '',
      langpref: '',
      favcategory: '',
      mylistopt: '',
      banneropt: '',
    });

    // 验证状态
    const usernameCheck = ref('');
    const passwordCheck = ref('');
    const repeatCheck = ref('');

    //获取用户信息
    onMounted(async () => {
        try {
            if (!accountStore || !accountStore.username) {
                console.error('未登录或未初始化账号状态');
                return;
            }
            const resp = await getUserInfo(accountStore.username);
            if (resp && resp.status === 0 && resp.data) {
                form.value = resp.data;
            } else {
                console.error('获取用户信息失败：', resp);
                signOnMsg.value = resp?.message || '获取用户信息失败';
            }
        } catch (err) {
            console.error('获取用户信息异常', err);
            signOnMsg.value = '网络异常，请稍后再试';
        }
    })


  
    // 验证函数
    function checkAccount() {
        usernameCheck.value = form.value.username ? 'OK' : '用户名不能为空';
    }
    function checkCode() {
      const pwd = form.value.password;
      const valid = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{8,}$/;
      passwordCheck.value = valid.test(pwd) ? 'OK' : '密码需至少8位并包含数字和字母';
    }
  
    function checkRepeatedCode() {
      repeatCheck.value = form.value.repeatPassword === form.value.password ? 'OK' : '密码不一致';
    }
  
    // 提交表单更新用户信息
    async function handleSubmit() {
        // 验证用户名、密码
        checkAccount();
        checkCode();
        checkRepeatedCode();
        if (usernameCheck.value === 'OK' && passwordCheck.value === 'OK' && repeatCheck.value === 'OK') {
        try {
            const response = await updateUserInfo(accountStore.username, form.value); // 调用 API 更新用户信息
            console.log('后端返回response：', response);
            if (response.status === 0) { 
                console.log('用户信息更新成功！');
                alert('更新成功！');
            } else {
                console.log('用户信息更新失败：response.status !== 0');
                signOnMsg.value = response.message || '更新失败!'; 
            }
        } catch (error) {
            console.error('更新失败：', error); // 异常捕获
            signOnMsg.value = error.response?.message || '更新失败，请稍后再试'; // 异常信息提示
        }
    }else{
        signOnMsg.value = '请修正上述错误';
    }
    }
</script>
    
<style scoped>
    input[type="text"],
    input[type="password"],
    input[type="email"] {
      width: 100%;
      max-width: 120px;
      padding: 6px 10px;
      margin: 6px 0;
      font-size: 14px;
      border: 1.5px solid #a87c5a;
      border-radius: 5px;
      background-color: #fffdfa;
      color: #734012;
      box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
      transition: border-color 0.2s ease, box-shadow 0.2s ease;
    }
  
    input[type="text"]:focus,
    input[type="password"]:focus,
    input[type="email"]:focus {
      outline: none;
      border-color: #fccc1c;
      background-color: #fffef4;
      box-shadow: 0 2px 5px rgba(252, 204, 28, 0.15);
    }
  
    input[type="text"]::placeholder,
    input[type="password"]::placeholder,
    input[type="email"]::placeholder {
      color: #b28e73;
      font-style: italic;
      opacity: 0.8;
    }
  
    span {
      color: #e74c3c;
      font-size: 12px;
      margin-left: 10px;
    }
  
    table {
      border-spacing: 0 10px;
    }
  
    td {
      padding: 5px;
    }
  
    td:first-child {
      text-align: right;
      padding-right: 15px;
    }
  
    input[type="submit"] {
      background-color: #f1c48f;
      color: white;
      padding: 10px 20px;
      border: none;
      border-radius: 5px;
      cursor: pointer;
      font-size: 16px;
      margin-top: 20px;
      width: auto;
      max-width: none;
    }
  
    input[type="submit"]:hover {
      background-color: #fcdc5e;
    }
  
    #BackLink {
      margin: 20px;
    }
  
    #BackLink a {
      color: #734012;
      text-decoration: none;
    }
  
    #BackLink a:hover {
      color: #fccc1c;
    }
  
    h3 {
      color: #734012;
      margin: 20px 0;
    }
  
    h4 {
      color: #b28e73;
      font-style: italic;
      margin: 10px 0;
    }
</style>
    